import type { CsDatePickerRangeProps } from 'csui'

type UseDatePickerProps<
  D extends Record<string, any>,
  P extends keyof Readonly<D>
> = UseFormItemProps<CsDatePickerRangeProps, D, P>

/**
 * 年份选择器 el-date-picker
 * @param propStart 开始时间绑定的prop
 * @param propEnd 结束时间绑定的prop
 * @param label item.label
 * @param props item的其他属性
 * @returns form-item-data
 */
export function useDatePickerRange<
  T extends Record<string, any>,
  P extends keyof T
>(
  propStart: P,
  propEnd: P,
  label: string,
  props: UseDatePickerProps<T, P> = {}
): FormItemProps<T, P> {
  const propName = `${String(propStart)}Obj`
  if (props.required && !props.rules) {
    props.rules = [
      {
        validator(rule, value, callback) {
          if (!value) {
            return callback(new Error(`${label}为必填项`))
          }
          if (value?.length && value.some((item: any) => !item)) {
            return callback(new Error(`${label}为必填项`))
          }
          callback()
        }
      }
    ]
  }
  return {
    label,
    prop: propName,
    change(value, items, formData) {
      formData[propStart] = value[0] || undefined
      formData[propEnd] = value[1] || undefined
    },
    ...props,
    component: 'cs-date-picker-range'
  }
}
